/*******************************************************************
 *   > File Name: mkv210.c
 *   > Author: fly
 *   > Mail: XXXXXXXX@icode.com
 *   > Create Time: 2020年04月19日 星期日 13时51分08秒
 ******************************************************************/
//计算前8kb(从第16字节开始)的校验和，写入文件头
//用于九鼎裸机开发使用
// 前16字节需要提前填充
/* egg:
 * bl1 header infomation for irom
 *
 * 0x0 - bl1 size
 * 0x4 - reserved (should be 0)
 * 0x8 - check sum
 * 0xc - reserved (should be 0)
 *
 *	.word 0x2000	// 自拷贝文件大小 
 *	.word 0x0
 *	.word 0x0
 *	.word 0x0
 */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFSIZE             (8*1024)
#define SPL_HEADER_SIZE     16

int main(int argc, char* argv[])
{
    FILE *fps;
    unsigned int checkSum = 0;
    int fileLen;
    char *Buf;
    
    int opt;
    while((opt = getopt(argc, argv, "v")) != -1)
    {
        switch(opt){
            case 'v':
            case 'V':
                printf("make_image v00.1\n");
                return 0;
                break;
            default:
                break;
        }
    }

    //Usage:./a.out src
    if(argc != 2){
        printf("Usage:%s <src file>\n", argv[0]);
        return -1;
    }

    //open source file
    if((fps = fopen(argv[1], "r+")) == NULL){
        printf("fopen %s err:%s\n", argv[1], strerror(errno));
        return (-1);
    }

    fseek(fps, 0L, SEEK_END);
    fileLen = ftell(fps);printf("fileLen:%dBytes\n",fileLen);
    fseek(fps, 15L, SEEK_SET);

    int n;
    char buf[1];
    int nbytes;
    
    //checksum
    while((n = fread(buf, 1, 1, fps)) > 0)
    {
        checkSum +=(0xff&buf[0]);
    }

    Buf = (char*)malloc(SPL_HEADER_SIZE);
    if(Buf == NULL){
        fclose(fps);
        puts("Alloc buffer failed!\n");return(-1);
    }
    memset(Buf, 0, SPL_HEADER_SIZE);

    *(unsigned int *)Buf = checkSum;

    fseek(fps, 8L, SEEK_SET);

    printf("checkSum:0x%x\n", checkSum);    
    
    //write checksum to file
    if((n=fwrite(Buf, 1,sizeof(unsigned int) ,fps)) != sizeof(unsigned int)){
        printf("fwrite err: %s\n", strerror(errno));
        fclose(fps);return -1;
    }

    if(fileLen < BUFSIZE){
        fseek(fps, 0L, SEEK_END);
        for(nbytes =0; nbytes < BUFSIZE -fileLen; nbytes ++){
            memset(buf, 0, 1);
            n = fwrite(buf, 1, 1, fps);
        }
        fileLen = ftell(fps);printf("NewfileLen:%dBytes\n",fileLen);
    }

    fclose(fps);

    return 0;
}
